package invoicesystem.controller;


import com.google.gson.Gson;
import invoicesystem.dao.AddressDao;
import invoicesystem.dao.EmailDao;
import invoicesystem.dao.impl.AddressDaoImpl;
import invoicesystem.dao.impl.EmailDaoImpl;
import invoicesystem.entry.*;
import invoicesystem.pojo.InvoicingApplyList;
import invoicesystem.pojo.OrderForm;
import invoicesystem.pojo.SelectTitleAndInvoic;
import invoicesystem.pojo.TotalAmountMess;
import invoicesystem.service.*;
import invoicesystem.service.impl.*;
import invoicesystem.util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;

@WebServlet("/system/*")
//相当于曾经的（“/book/*”）
public class InvoicesystemServlet extends HttpServlet {
    private OrderService orderService=new OrderServiceImpl();
    private InvoicingRecordService invoicingRecordService=new InvoicingRecordServiceImpl();
    private BaseDataService baseDataService=new BaseDataServiceImpl();
    private UserService userService=new UserServiceImpl();
    private AddressService addressService=new AddressServiceImpl();
    private EmailService emailService=new EmailServiceImpl();

    Gson gson = new Gson();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, UnsupportedEncodingException {
        //  super.service(req, resp);
        //0.处理乱码：
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //获得请求路径
        String url= request.getRequestURI();
        String methodName= url.substring(url.lastIndexOf("/")+1);//从末尾截取地址最后一个
        Class cla= InvoicesystemServlet.class;
        Method method = null;
        try {
            method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);//获得方法名和参数类型与上面代码获取的内容一样的方法
            method.invoke(cla.newInstance(),request,response);//动态调用方法，逗号前为方法名，后为方法参
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
    //根据登录用户所带的公司id查询数据库中表头信息，
    public void queryTitle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BaseDataService baseDataService=new BaseDataServiceImpl();
        BaseData baseData= baseDataService.selectBaseData(Integer.parseInt(request.getParameter("enterprise_id")));
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(baseData));
    }
    //根据登录用户所带的公司id查询数据库中默认邮寄地址
    public void queryAddressDefalut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AddressService addressService=new AddressServiceImpl();
        Address address=new Address();
        address.setEnterprise_id(Integer.parseInt(request.getParameter("enterprise_id")));
        //搜索默认状态的数据
        Address address2=addressService.selectByIdAndStatus(address);
        Gson gson=new Gson();
        response.getWriter().println((gson.toJson(address2)));
    }
    //根据登录用户所带的公司id查询数据库中电子邮箱
    public void queryEmailDefalut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        EmailService emailService=new EmailServiceImpl();
        Email email=emailService.selectDefalut(Integer.parseInt(request.getParameter("enterprise_id")));
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(email));
    }
    //获得数据库中BaseData表数据
    public  void getBaseData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BaseDataService baseDataService=new BaseDataServiceImpl();
        Gson gson =new Gson();
        response.getWriter().println(gson.toJson(baseDataService.getAll(Integer.parseInt(request.getParameter("enterprise_id")))));
    }
    //修改数据库中BaseData表中的开户银行，开户账号，注册固定电话，注册场所地址
   public void updateBaseData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BaseData baseData=new BaseData();
        baseData.setBank_name(request.getParameter("bank_name"));
        baseData.setBank_account(request.getParameter("bank_account"));
        baseData.setPhone(request.getParameter("phone"));
        baseData.setAddress(request.getParameter("address"));
        baseData.setTax_no(request.getParameter("tax_no"));
        BaseDataService baseDataService=new BaseDataServiceImpl();
        boolean uncertain=  baseDataService.updateBaseData(baseData);
        //1表示修改成功，0表示修改失败
        int a=uncertain?1:0;
        response.getWriter().println(a);
   }
    //在数据库中的Address表中添加数据
    public  void  insertAddress(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Address address=new Address();
        address.setEnterprise_id(Integer.parseInt(request.getParameter("enterprise_id")));
        address.setAddressee(request.getParameter("addressee"));
        address.setPhone(request.getParameter("phone"));
        address.setArea(request.getParameter("area"));
        address.setAddress_detail(request.getParameter("address_detail"));
        //地址状态初始值都是“普通”
        address.setDefault_status("普通");
        AddressService addressService=new AddressServiceImpl();
            //a等于0添加失败
            int a= addressService.insertAddress(address);

          response.getWriter().println(a);
    }
    //在数据库中的Address表中修改数据
    public void  updateAddress(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Address address=new Address();
        address.setId(Integer.parseInt(request.getParameter("id")));
        address.setAddressee(request.getParameter("addressee"));
        address.setPhone(request.getParameter("phone"));
        address.setArea(request.getParameter("area"));
        address.setAddress_detail(request.getParameter("address_detail"));
        AddressService addressService=new AddressServiceImpl();
        //a等于0添加失败
        int a= addressService.updateAddress(address);
        response.getWriter().println(a);
    }
    //根据公司id查询Address表信息
    public void queryAddress(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AddressService addressService=new AddressServiceImpl();
        ArrayList<Address> list =addressService.select(Integer.parseInt(request.getParameter("enterprise_id")));
        Gson gson=new Gson();
        response.getWriter().println((gson.toJson(list)));
    }
    //无条件查找Address所有数据
//    public  void queryAllAddress(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        AddressService addressService=new AddressServiceImpl();
//        ArrayList<Address> list =addressService.selectAll();
//        Gson gson=new Gson();
//        response.getWriter().println((gson.toJson(list)));
//    }
    //为Address设置默认状态
    //设置Address默认状态
    public  void  changeStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AddressService addressService=new AddressServiceImpl();
        Address address=new Address();
        address.setEnterprise_id(Integer.parseInt(request.getParameter("enterprise_id")));
        //address2 ：之前状态为默认的数据，在service已经过滤了非默认数据
        Address address2=addressService.selectByIdAndStatus(address);
        //   将之前默认状态数据设为普通
        Address address3=new Address();
        address3.setDefault_status("普通");
        address3.setId(address2.getId());
        addressService.updateStatus(address3);
        //要设为默认的属性的序号
         int inId =Integer.parseInt(request.getParameter("id"));
         //address4:进行新默认状态设置的对象
        Address address4=new Address();
        address4.setId(inId);
        address4.setDefault_status("默认");
        //a为0设置失败
      int a=  addressService.updateStatus(address4);
      response.getWriter().println(a);
    }


    //查数据库中Email中数据
    public  void queryEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        EmailService emailService=new EmailServiceImpl();
        Email email=new Email();
        email.setEnterprise_id(Integer.parseInt(request.getParameter("enterprise_id")));
        ArrayList<Email> list=emailService.select(email);
        Gson gson=new Gson();
        response.getWriter().println((gson.toJson(list)));
    }
    //在数据库中Email中添加数据
    public  void insertEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        EmailService emailService=new EmailServiceImpl();
        Email email =new Email();
        email.setEnterprise_id(Integer.parseInt(request.getParameter("enterprise_id")));
        email.setEmail_detail(request.getParameter("email_detail"));
        email.setDefault_status("普通");
        //非0表示添加成功；0表示添加失败
        int a= emailService.insertEmail(email);
        response.getWriter().println(a);
    }
    //修改Email表数据
    public  void updateEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
             Email email=new Email();
             email.setId(Integer.parseInt(request.getParameter("id")));
             email.setEnterprise_id(Integer.parseInt(request.getParameter("enterprise_id")));
             email.setEmail_detail(request.getParameter("email_detail"));
             EmailService emailService=new EmailServiceImpl();
             //a为0，修改失败；非0成功
            int a= emailService.updateEmail(email);
             response.getWriter().println(a);
    }
    //无条件查询Email表所有数据
//    public  void  queryAllEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        ArrayList<Email> list=new ArrayList<>();
//        EmailService emailService=new EmailServiceImpl();
//        list=emailService.selectAll();
//        Gson gson=new Gson();
//        response.getWriter().println(gson.toJson(list));
//
//    }
    //设置Email默认状态
    public  void  changeEStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        EmailService emailService=new EmailServiceImpl();
        //email ：之前状态为默认的数据，在service已经过滤了非默认数据
        Email email=emailService.selectDefalut(Integer.parseInt(request.getParameter("enterprise_id")));
        //   将之前默认状态数据设为普通
        Email email1=new Email();
        email1.setDefault_status("普通");
        email1.setId(email.getId());
        emailService.updateStatus(email1);

        //要设为默认的属性的序号
        int inId =Integer.parseInt(request.getParameter("id"));
        //email2:进行新默认状态设置的对象
        Email email2=new Email();
        email2.setId(inId);
        email2.setDefault_status("默认");
        //a为0设置失败
        int a=  emailService.updateStatus(email2);
        response.getWriter().println(a);
    }

    //----------------mo&liu
    //按查询开票列表
    public void queryByInvoicingRecord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SelectTitleAndInvoic selTit=new SelectTitleAndInvoic();
        //接收参数
        //接收企业id
        Integer enterprise_id = Integer.parseInt(request.getParameter("enterprise_id"));
        selTit.setEnterprise_id(enterprise_id);
        //接收创建时间
        String create_time = request.getParameter("create_time");
        if(create_time!=null && create_time.length()>0){
            selTit.setCreate_time(create_time);
        }
        //接收抬头
        String title = request.getParameter("title");
        if(title!=null && title.length()>0){
            selTit.setTitle(title);
        }
        //接收最小金额和最大金额
        if (request.getParameter("minamount")!=null&&request.getParameter("minamount").length()>0){
            Double minamount = Double.parseDouble(request.getParameter("minamount"));
            selTit.setMinamount(minamount);
        }
        if (request.getParameter("maxamount")!=null&&request.getParameter("maxamount").length()>0){
            Double maxamount = Double.parseDouble(request.getParameter("maxamount"));
            selTit.setMaxamount(maxamount);
        }
        //接收状态
        if (request.getParameter("status")!=null&&request.getParameter("status").length()>0) {
            if (request.getParameter("status").equals("申请中")) {
                selTit.setStatus("申请中");
            } else if (request.getParameter("status").equals("已开票")) {
                selTit.setStatus("已开票");
            } else if (request.getParameter("status").equals("已作废")) {
                selTit.setStatus("已作废");
            }
        }
        //接收当前是第几页
        String index=request.getParameter("pageindex");
        PageHelper pageHelper = new PageHelper();
        if (index!=null){
            pageHelper.setIndexPage(Integer.parseInt(index));
        }
        ArrayList<InvoicingApplyList> invoicingApplyLists = invoicingRecordService.selectByCreate_timeOrByTitleOramount(selTit,pageHelper);
        pageHelper.setList(invoicingApplyLists);
        pageHelper.setCountData(invoicingRecordService.selectInvoicSize(selTit));
        response.getWriter().println(gson.toJson(pageHelper));

    }

    //退票操作
    public void refund(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Integer invoicingRecordId=Integer.parseInt(request.getParameter("refundId"));
        response.getWriter().println(gson.toJson(invoicingRecordService.returnInvoicingRecord(invoicingRecordId)));

    }

    public void queryAll(HttpServletRequest request, HttpServletResponse response)throws IOException{
        ArrayList list = userService.login(request.getParameter("account"),request.getParameter("password"));
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(list));
    }

    public void selectOrder(HttpServletRequest request, HttpServletResponse response)throws IOException{
        ArrayList users = orderService.selectOrder(Integer.parseInt(request.getParameter("enterprise_id")));
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(users));
    }


    public void selectMultitable(HttpServletRequest request, HttpServletResponse response)throws IOException{
        ArrayList users = invoicingRecordService.selectMultitable(Integer.parseInt(request.getParameter("id")));
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(users));
    }


    public void selectemail_id(HttpServletRequest request, HttpServletResponse response)throws IOException{
        ArrayList userss = invoicingRecordService.selectemail_id(Integer.parseInt(request.getParameter("email_id")));
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(userss));
    }
    //盛志健
    public void selectByid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String enterprise_id = "888888";
        //获得未开票的数据
        ArrayList<Order> listB = orderService.selectByidAndSttausA(Integer.parseInt(enterprise_id));
        //获得已开票的数据
        ArrayList<Order> listA = orderService.selectByidAndSttausB(Integer.parseInt(enterprise_id));
        //调用pojo类
        TotalAmountMess totalAmountMess = new TotalAmountMess();
        //获得未开票的全部数据的和
        Double sumA=0.0;
        for(Order order:listA){
            sumA+=order.getTotal_amount();
        }
        //获得已开票的数据的和
        Double sumB=0.0;
        for(Order order:listB){
            sumB+=order.getTotal_amount();
        }
        //设置值
        totalAmountMess.setMessA(sumA);
        totalAmountMess.setMessB(sumB);
        totalAmountMess.setMess(sumA+sumB);
        //输出值
        response.getWriter().println(new Gson().toJson(totalAmountMess));
    }
    public void queryByOrderForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //接收数据
        String no=request.getParameter("no");
        String create_time=request.getParameter("create_time");
        String minTotal_amount=request.getParameter("minTotal_amount");
        String maxTotal_amount=request.getParameter("maxTotal_amount");
        //准备参数
        Order order=new Order();
        OrderForm orderForm=new OrderForm();
        if(no!=null){
            order.setNo(no);
        }
        if(create_time!=null){
            order.setCreate_time(create_time);
        }
        if(minTotal_amount!=null && !minTotal_amount.isEmpty()){
            Double min=Double.parseDouble(minTotal_amount);
            orderForm.setMinTotal_amount(min);
        }
        if(maxTotal_amount!=null && !maxTotal_amount.isEmpty()){
            Double max=Double.parseDouble(minTotal_amount);
            orderForm.setMaxTotal_amount(max);
        }
        ArrayList<Order> list=orderService.selectAll(order,orderForm);
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(list));
    }
    //更新order表的数据
    public void updateOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        int enterprise_id=Integer.parseInt(request.getParameter("enterprise_id"));
        String no=request.getParameter("no");
        boolean b=orderService.updateOrder(enterprise_id,no);
        response.getWriter().println(b);
    }
    //添加InvoicingRecord数据
    public void insertInvoicingRecord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //传order的订单编号
        String no=request.getParameter("no");
        boolean b1 = orderService.updateOrderno(no);

        String type=request.getParameter("type");
        String category=request.getParameter("category");
        int enterprise_id=Integer.parseInt(request.getParameter("enterprise_id"));
        BaseData baseData=baseDataService.selectById(enterprise_id);
        User user=userService.selectByid(enterprise_id);
        String email=request.getParameter("email");
        Email email1=emailService.selectByEmail_detail(email);
        String address=request.getParameter("address");
        Address address1=addressService.selectByAddress(address);
        String amount=request.getParameter("amount");
        Double double2=null;
        if(!amount.isEmpty()){
            double2=Double.parseDouble(amount);
        }
        InvoicingRecord invoicingRecord=new InvoicingRecord(double2,enterprise_id,user.getId(),category,type,baseData.getId(),address1.getId(),email1.getId());
        boolean b=invoicingRecordService.insertInvoicingRecord(invoicingRecord);
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(b));

    }
    public void selectaddress(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AddressDao addressDao=new AddressDaoImpl();
        ArrayList<Address> list=addressDao.selectAll(1);
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(list));
        /*int enterprise_id = Integer.parseInt(request.getParameter("enterprise_id"));
        ArrayList<Address> list = addressService.selectById(enterprise_id);
        Gson gson =new Gson();
        response.getWriter().println(gson.toJson(list));*/
    }
    public void selectemail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int enterprise_id = Integer.parseInt(request.getParameter("enterprise_id"));
        ArrayList<Email> list = emailService.selectById(enterprise_id);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(list));
    }
    public void selectbyenterprise_id(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int enterprise_id =Integer.parseInt( request.getParameter("enterprise_id"));
        BaseData baseData = baseDataService.selectById(enterprise_id);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(baseData));
    }
    public  void  selectbyno(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        EmailDao emailDao=new EmailDaoImpl();
        ArrayList<Email> emails = emailDao.selectAll(1);
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(emails));
    }
    public void selectEmailDefault(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        EmailService emailService=new EmailServiceImpl();
        String enterprise_id = request.getParameter("enterprise_id");
        Email email=emailService.selectDefault(Integer.parseInt(enterprise_id));
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(email));
    }
    public void selectAddressDefault(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        AddressService addressService=new AddressServiceImpl();
        String enterprise_id = request.getParameter("enterprise_id");
        Address address=addressService.selectDefault(Integer.parseInt(enterprise_id));
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(address));
    }
    public void updateInvoicingRecord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String status=request.getParameter("status");
        String uplink_address=request.getParameter("uplink_address");
        InvoicingRecord invoicingRecord=new InvoicingRecord(status,uplink_address);
        boolean b=invoicingRecordService.updateInvoicingRecord(invoicingRecord);
        response.getWriter().println(b);
    }
    public void kaipiao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        InvoicingRecordService invoicingRecordService=new InvoicingRecordServiceImpl();
        String total_amount = request.getParameter("total_amount");
        //Double total=Double.parseDouble(total_amount);
        String create_time = request.getParameter("create_time");
        String kindname = request.getParameter("kindname");
        String kinde = request.getParameter("kinde");
        System.out.println(kindname);
        System.out.println(kinde);
        InvoicingRecord invoicingRecord=new InvoicingRecord();


        invoicingRecord.setAmount(Double.parseDouble(total_amount));
        invoicingRecord.setCreate_time(create_time);
        invoicingRecord.setCreator_id(888888);
        invoicingRecord.setCategory(kindname);
        invoicingRecord.setType(kinde);
        invoicingRecord.setStatus("已开票");

        UUID uuid=UUID.randomUUID();
        String uid = uuid.toString().substring(0,8);
        System.out.println(uid);
        invoicingRecord.setUplink_address(uid);
        boolean B = invoicingRecordService.updateInvoicingRecord(invoicingRecord);
        System.out.println(B);
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(B));

    }



}
